import { Modal,ConfigProvider,Form, Input, Button, Table, Switch, Select, DatePicker } from 'antd';
import React,{ useEffect, useState } from 'react';
import zh_CN from 'antd/es/locale/zh_CN';
import type { ColumnsType } from 'antd/es/table';
import { useNavigate,useLocation } from 'react-router-dom';
import './Css/Promontion.less'
import '../../css/public.less'
import LocationAlter from './child/LocationAlter';
import AddCommodity from './AddCommodity';
import { ExclamationCircleFilled } from '@ant-design/icons';
import {goodsValue,delGoodsApi} from '../../../api/wj'
import Item from 'antd/es/list/Item';
import { number } from 'echarts';
//Commodity 罗文江的名字 CommodityManagement我的名字
function Commodity() {
    //表格数据类型
    interface DataType {
        key: React.Key; //id
        id: number //序号
        img: string //图片
        name: string; //商品名
        sernum: string //货号
        price: string //价格
        rec: string //分类
        sell: number //销量
        seat: string; //使用行程
        state: number //以未上架判断
    }
    const [count,setCount] = useState<number>()//用条数
    const { confirm } = Modal;
    //排序的方式名
    const [sortName,setSortName] = useState<{value:string,label:string}[]>([{ value: '升序', label: '升序' },{ value: '降序', label: '降序' }])
    //当前页码
    const [nowPage, setNowPage] = useState<number>(1)
    //总条数
    const [totalPage,setTotalPage] = useState<number>(5)
    //路由跳转
    const navigate = useNavigate()
    //促销id
    const [promotionId,setPromotionId] = useState(Number)
    //用户数据
    const [data,setData] = useState()
    //s使用路由传参
    const state = useLocation()
    console.log('state闯过来的数据',state);
    const [type, setType] = useState<{ sportId: number, sportName: string }[]>(state.state)
    //查看弹框显示布尔值
    const [isModalOpen, setIsModalOpen] = useState(false);
    //点击位置按钮时的数据
    const [seat, setSeat] = useState<DataType | null>()
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'id',
        },
        {
            title: '商品图片',
            dataIndex: 'img',
            render: (_, v) => (
                // <img
                //     width={100}
                //     height={50}
                //     src={v.img} alt="" />
                <p>{v.img}</p>
            )
        },
        {
            title: '货号',
            dataIndex: 'sernum',
        },
        {
            title: '价格',
            dataIndex: 'price',
        },
        {
            title: '分类',
            dataIndex: 'rec',
        },
        {
            title: '销量',
            dataIndex: 'sell',
        },
        {
            title: '位置',
            dataIndex: 'seat',
        },
        {
            title: '是否上架',
            dataIndex: 'state',
            render: (_, v) =>
            (
                <Switch
                    defaultChecked={v.state==4?true:false}
                    onChange={onChange}
                    onClick={() => { switchClick(v) }} />
            )
        },
        {
            title: '操作',
            dataIndex: 'address',
            width: 310,
            render: (_, v) => (
                <div className='operationList'>
                    {/* <button className='man' onClick={() => { commodityBtn(v) }}>查看</button> */}
                    <button className='edit' onClick={() => { redactBtn(v) }}>位置</button>
                    <button className='del' onClick={() => { showPromiseConfirm(v) }}>删除</button>
                </div>
            )
        },
    ];
    useEffect(()=>{
        getvalue()
    },[nowPage,totalPage])
    const getvalue = ()=>{
        goodsValue(
            {id:state.state.id,num:nowPage,size:totalPage}
            ).then(res=>{
                console.log('商品数据陈宫',res);
                if(res.code=='200'){
                    setData(res.data.goods)
                    setCount(res.data.total)
                }
            }).catch(err=>{
                console.log(err);
                
            })
    }
    //存储促销id
    // setPromotionId(state.state.id)
    //switch的change方法
    const onChange = (checked: boolean) => {
        // checked ? checked=true:checked=false
        console.log(`switch to ${checked}`);
    };
    //更改上架状态
    const switchClick = (v: {}) => {
        console.log(`switchClick事件获取到的`, v);
    }
    //点击位置显示弹框
    const redactBtn = (v:DataType) => {
        console.log('点击位置事件触发的', v)
        setIsModalOpen(true)
        setSeat(v)//存储位置数目
    }
    //让位置弹框关闭
    const closeModal = () => {
        setIsModalOpen(false)
    }
    // //点击删除
    // const del = (v: any) => {
    //     console.log('删除的点击事件触发', v);
    // }
    const showPromiseConfirm = (v:any) => {
        confirm({
            title: '确认删除此信息',
            icon: <ExclamationCircleFilled />,
            content: 'When clicked the OK button, this dialog will be closed after 1 second',
            onOk() {
                return new Promise(async (resolve, reject) => {
                    setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
                    console.log(v);
                    let res = await delGoodsApi({id:v.id,pro:promotionId})
                    console.log(res);
                    if(res.code == '200'){
                        getvalue()
                    }
                    
                }).catch((reject) => console.log('Oops errors!',reject));
            },
            onCancel() { },
        });
    };
    //父组件存储子元素传过来的值的容器
    const [getValue,setGetValue] = useState<{}>()
    //父组件接受子组件值的方法
    const getChild=(val:{})=>{
        setGetValue(val)
        console.log('子组件传过来的值',getValue);
    }
    //表格方法(勾选的内容)
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        //switch勾选的内容
        console.log('selectedRowKeys changed switch勾选的内容: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
        console.log('SelectedRowKeys', selectedRowKeys);
    };
    const rowSelection = {
        // selectedRowKeys,
        onChange: onSelectChange,
    };
    //当前页码和页数
    const changePage=(page: number, pageSize: number):void=>{
        console.log('页码变了了', page, pageSize);
        setNowPage(page),
        setTotalPage(pageSize)
    }
    //跳转到添加商品页面
    const AddCommodityBtn=()=>{
        sessionStorage.setItem('value',JSON.stringify(state.state.id))
        navigate(`/home/promotion/AddCommodity`)
    }
    return (
        <div className='Promotionma'>
            {/* 头部 */}
            <div className='page-top'>
                <div className='page-title'>
                    <p>促销</p>
                </div>
            </div>
            {/* 内容框 */}
            <div className='data-list'>
                <div className='headChoose'>
                    {/* 标题 */}
                    <p>商品列表</p>
                    <div>
                        {/* 排序方式 */}
                        <p style={{marginRight:"10px"}}>排序方式:</p>
                        <Select
                        style={{ width: 120 }}
                        options={sortName}
                        />
                        {/* 添加按钮 */}
                        <button className='add' onClick={AddCommodityBtn} style={{marginLeft:'10px'}}>添加商品</button>
                    </div>
                </div>
                <div className='contentType'>
                    <div style={{ marginBottom: 16 }}>
                    </div>
                    <ConfigProvider locale={zh_CN}>
                    <Table rowSelection={rowSelection}
                        columns={columns}
                        dataSource={data}
                        scroll={{ y: 444 }}
                        rowKey={item=>item.id}
                        pagination={{
                            position: ['bottomCenter'],
                            defaultPageSize: 5,
                            pageSizeOptions: [3, 5, 10, 15],
                            showQuickJumper: true,
                            showSizeChanger: true,
                            total:count,
                            onChange: changePage
                        }} />
                        </ConfigProvider>
                </div>
            </div>
            {/* 查看位置子组件 */}
            <LocationAlter getChild={getChild} isModalOpen={isModalOpen} closeModal={closeModal} seat={seat}></LocationAlter>
        </div>
    )
}
export default Commodity
// 商品管理页面